package com.honey.compilation.sql.ddl;

import com.honey.compilation.sql.SqlConstraint;
import com.honey.compilation.sql.SqlKeyWord;
import com.honey.compilation.sql.ValueElement;
import com.honey.core.builder.CharacterBuilder;
import com.honey.core.builder.CharacterBuilderFactory;
import com.honey.core.compiler.IndentSpace;
import com.honey.core.utils.StringUtility;

/**
 * PRIMARY KEY 约束 
 * @author Administrator
 *
 */
public class ConstraintPrimarykey extends SqlConstraint{

	private ValueElement primarykeyName ;
	
	private static int index = 0;
	
	/** 是否添加随机的约束名称*/
	private boolean addRandomConstraintName = true;
	
	/**
	 *  默认的构造函数, 主键的名称使用随机数
	 */
	public ConstraintPrimarykey (){
		
	}
	
	/**
	 * 构造函数,是否使用随机唯一约束名称 true:是  false:否<br />
	 * 如果指定主键的名称,随机生成主键名称失效,使用指定的主键名称. <br />
	 * @param addRandomConstraintName 是否添加随机的约束名称,true:是  false:否
	 */
	public ConstraintPrimarykey (boolean addRandomConstraintName){
		this.addRandomConstraintName = addRandomConstraintName;
	}
	
	/**
	 * 构造函数,指定主键的名称<br />
	 * 如果指定主键的名称,随机生成主键名称失效,使用指定的主键名称.<br />
	 * @param primarykeyName
	 */
	public ConstraintPrimarykey (String primarykeyName){
		if ( StringUtility.stringHasValue(primarykeyName ) ){
			this.primarykeyName = new ValueElement( primarykeyName );
		}
	}
	
	/**
	 * 是否添加随机的约束名称,true:是  false:否<br />
	 * 如果指定主键的名称,此参数失效,使用指定的主键名称.
	 * @return
	 */
	public boolean isAddRandomConstraintName() {
		return addRandomConstraintName;
	}
	
	/**
	 * 是否添加随机的约束名称,true:是  false:否<br/>
	 * 如果指定主键的名称,此参数失效,使用指定的主键名称.
	 * @param addRandomConstraintName
	 */
	public void setAddRandomConstraintName(boolean addRandomConstraintName) {
		this.addRandomConstraintName = addRandomConstraintName;
	}
	
	@Override
	public SQLConstraintType getSQLConstraintType() {
		
		return SQLConstraintType.PRIMARY_KEY;
	}

	@Override
	public CharacterBuilder compiledContent(int indentLevel) {
		CharacterBuilder answer = CharacterBuilderFactory.createC16StringBuilder();
		IndentSpace.spaceIndent(answer, indentLevel);
		if( addRandomConstraintName && primarykeyName == null){
			primarykeyName =new ValueElement (
					CharacterBuilderFactory.createC16StringBuilder()
					.append(SqlKeyWord.OPERATION_UNDERSCORE)
					.append("pk").append(index)
					.append(SqlKeyWord.OPERATION_UNDERSCORE)
					.append(  StringUtility.getRandomString(6) )
					.append(SqlKeyWord.OPERATION_UNDERSCORE).toString()
			);
			index ++ ;
			answer.append(SqlKeyWord.CONSTRAINT )
			.append(primarykeyName);
		}else if( primarykeyName != null ){
			answer.append(SqlKeyWord.CONSTRAINT )
			.append(primarykeyName);
		}
		
		answer.append(SqlKeyWord.PRIMARY)
		.append(SqlKeyWord.KEY);
		
		return answer;
	}
}
